package projectjet;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.net.Socket;

public class Autentification {
   private AuthService authService = new AuthService();
   private Socket socket;
   private BufferedReader in;
   private BufferedWriter out;
   private String username;
   private Session session;
   
   public Autentification(Socket socket, BufferedReader in, BufferedWriter out, Session session ){
       this.socket = socket;
       this.in = in;
       this.out = out; 
       this.session = session;
   }
   
   public boolean getAuthentication(){
       String userLoginPassword = getUserLoginPass();
        authService.connection();
        while(!session.isInterrupted() && !authService.checkSecurity(userLoginPassword)){
                send("Your Authorization faild. Try again. Enter your login: ");
                userLoginPassword = getUserLoginPass();
        }
        username = userLoginPassword.split(" ")[0];
        send("HELLO " + username);
        return true;
    }

   public String getUserLoginPass() {
        String userLoginPass = "";
        try{
            userLoginPass = this.in.readLine();
            send("Enter your password: ");
            userLoginPass += " " + this.in.readLine();

        }catch(Exception e){
                System.out.println("Error authorization: " + e.getMessage());

                if(this.socket != null)

                    try {
                            this.socket.close();
                    } catch (IOException e1) {
                            System.out.println("Error closed socket: " + e1.getMessage());
                    }
                session.interrupt();
        }
        return userLoginPass;
    }

   public String getUsername(){
        return username;
    }
   
    public void send(String message){
        try{
            this.out.write(message + "\n");
            this.out.flush();
        }catch(IOException e){
            System.out.println("Error sending message: " + e.getMessage());
        }
    }

}
